package com.example.graduation.service.impl;

import com.example.graduation.config.CosConfig;
import com.example.graduation.exception.MyException;
import com.example.graduation.mapper.EvaluateMapper;
import com.example.graduation.service.FileOperationService;
import com.example.graduation.util.JwtUtil;
import com.example.graduation.util.R;
import com.example.graduation.form.FileDForm;
import com.example.graduation.form.FileUForm;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.DeleteObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * ProjectName graduation
 *
 * @author xieyucan
 * <br>CreateDate 2022/2/26 15:40
 */
@Slf4j
@Service
public class FileOperationServiceImpl implements FileOperationService {

    @Resource
    private CosConfig cosConfig;

    @Resource
    private JwtUtil jwtUtil;


    /**
     * 删除临时文件
     *
     * @param files
     * @author xieyucan
     * CreateDate 2022/2/26 16:26
     */
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }


    /**
     * 使用腾讯云存储桶上传文件
     *
     * @param file
     * @param token
     * @return {@link R}
     * @author xieyucan
     * CreateDate 2022/3/22 17:03
     */
    @Override
    public R upload(MultipartFile file, String token) {
        int userId = jwtUtil.getUserIdByToken(token);
        if (file == null) {
            return R.error(404, "文件夹为空");
        }
        //获取文件的名称
        String oldFileName = file.getOriginalFilename();
        log.info("获取到的文件名称:{}", oldFileName);
        //获取文件扩展名
        String endName = oldFileName.substring(oldFileName.lastIndexOf("."));
        //拼接新的文件名称
        String newFileName = System.currentTimeMillis() + endName;
        log.info("修改后的文件名称:{}", newFileName);
        //1:初始化用户信息
        COSCredentials cred = new BasicCOSCredentials(cosConfig.getAccesskey(), cosConfig.getSecretKey());
        // 2:设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(cosConfig.getBucket()));
        //3: 生成cos客户端
        COSClient client = new COSClient(cred, clientConfig);
        log.info("腾讯云客户端连接成功");
        //4:填写存储桶的名称，在此需要符合存储桶名称的格式规则 {name}-{appId}
        String bucketName = cosConfig.getBucketName();
        File localFile = null;
        try {
            //创建临时文件，设置前缀和后缀
            localFile = File.createTempFile("temp", null);
            file.transferTo(localFile);
            //设置指定上传位置
            String key = "/" + cosConfig.getQianzui() + "/" + userId + "/" + newFileName;
            log.info("文件上传路径:{}", key);
            PutObjectRequest request = new PutObjectRequest(bucketName, key, localFile);
            //客户端上传文件
            PutObjectResult result = client.putObject(request);
            log.info("文件上传成功");
            deleteFile(localFile);
            log.info("删除临时文件成功");
            return R.ok().put("path", cosConfig.getPath() + request.getKey());
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException("文件上传失败");
        } finally {
            client.shutdown();
        }
    }


    /**
     * 删除腾讯云存储桶中的文件
     *
     * @param form
     * @return {@link R}
     * @author xieyucan
     * CreateDate 2022/3/22 17:03
     */
    @Override
    public R delete(FileDForm form) {
        COSClient client = null;
        try {
            //1:初始化用户信息
            COSCredentials cred = new BasicCOSCredentials(cosConfig.getAccesskey(), cosConfig.getSecretKey());
            // 2:设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
            ClientConfig clientConfig = new ClientConfig(new Region(cosConfig.getBucket()));
            //3: 生成cos客户端
            client = new COSClient(cred, clientConfig);
            //4:填写存储桶的名称，在此需要符合存储桶名称的格式规则 {name}-{appId}
            String bucketName = cosConfig.getBucketName();
            DeleteObjectRequest request = new DeleteObjectRequest(bucketName, form.getKey());
            /**
             * 删除数据
             */
            client.deleteObject(request);
            return R.ok("文件删除成功").put("path", cosConfig.getPath() + request.getKey());
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException("文件删除失败");
        } finally {
            client.shutdown();
        }
    }
}
